﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmartSpace.Core
{
    public partial class CoreService : ICoreService
    {
        public ServiceResult SaveCodeDefinition(CodeDefinition code)
        {
            using (CoreDbContext context = new CoreDbContext())
            {
                if (!EntityRepository.SaveCodeEntity(code, context))
                {
                    return new ServiceResult(false);
                }

                return new ServiceResult(EntityRepository.Commit(context));
            }
        }

        public List<CodeDefinition> GetCodeDefinitions(string categoryCode)
        {
            using (CoreDbContext context = new CoreDbContext())
            {
                return context.Set<CodeDefinition>()
                    .Join(context.Set<CodeCategory>().Where(p => p.Code == categoryCode),
                    l => l.CategoryId,
                    r => r.Id,
                    (l, r) => l).OrderBy(p => p.Code).ToList();
            }
        }

        public List<CodeDefinition> GetCodeDefinitions(Guid categoryId)
        {
            using (CoreDbContext context = new CoreDbContext())
            {
                return context.Set<CodeDefinition>().Where(p => p.CategoryId == categoryId).OrderBy(p => p.Code).ToList();
            }
        }

        public CodeDefinition GetCodeDefinition(Guid id)
        {
            using (CoreDbContext context = new CoreDbContext())
            {
                return context.Set<CodeDefinition>().Where(p => p.Id == id).SingleOrDefault();
            }
        }

        public ServiceResult SaveCodeCategory(CodeCategory category)
        {
            using (CoreDbContext context = new CoreDbContext())
            {
                if (!EntityRepository.SaveCodeEntity(category, context))
                {
                    return new ServiceResult(false);
                }

                return new ServiceResult(EntityRepository.Commit(context));
            }
        }

        public List<CodeCategory> GetCodeCategories()
        {
            using (CoreDbContext context = new CoreDbContext())
            {
                return context.Set<CodeCategory>().OrderBy(p => p.Code).ToList();
            }
        }

        public CodeCategory GetCodeCategory(Guid id)
        {
            using (CoreDbContext context = new CoreDbContext())
            {
                return context.Set<CodeCategory>().Where(p => p.Id == id).SingleOrDefault();
            }
        }
    }
}
